<template>
  <div class="h-full flex flex-col bg-[#fff] px-[15px] justify-between">
    <div class="grow-[1] h-0 py-[15px]">
      <el-table
        scrollbar-always-on
        ref="elTableRef"
        v-loading="state.loading"
        :data="state.list"
        height="100%"
        border
        stripe
        fit
      >
        <el-table-column align="center" label="序号" width="120">
          <template #default="{ row }: TableItem">
            <el-input-number
              class="!w-full"
              :min="0"
              v-model="row.LotterySort"
              :precision="0"
              :controls="false"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Name" label="游戏名称" />
        <el-table-column align="center" prop="Status">
          <template #header>
            <div class="flex items-center justify-center">开启游戏</div>
            <div>
              <el-switch
                size="large"
                inline-prompt
                active-text="开启"
                inactive-text="关闭"
                v-model="state.status"
              />
            </div>
          </template>
          <template #default="{ row }: TableItem">
            <el-switch
              size="large"
              active-text="开启"
              inactive-text="关闭"
              inline-prompt
              v-model="row.Status"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="CloseCount">
          <template #header>
            <div class="flex items-center justify-center">提前封盘时间/秒</div>
            <div>
              <el-input-number
                v-model="state.closeCount"
                :max="100"
                :min="0"
                :precision="0"
                :controls="false"
              />
            </div>
          </template>
          <template #default="{ row }: TableItem">
            <el-input-number
              v-model="row.CloseCount"
              :max="100"
              :min="0"
              :precision="0"
              :controls="false"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="OpenTime">
          <template #header>
            <div class="flex items-center justify-center">自动开启</div>
            <div>
              <el-time-picker
                class="!w-full"
                v-model="state.openTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                @change="handleOpenChange"
              />
            </div>
          </template>
          <template #default="{ row }: TableItem">
            <el-time-picker
              class="!w-full"
              v-model="row.OpenTime"
              format="HH:mm:ss"
              value-format="HH:mm:ss"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="CloseTime">
          <template #header>
            <div class="flex items-center justify-center">自动结束</div>
            <div>
              <el-time-picker
                class="!w-full"
                v-model="state.closeTime"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                @change="handleCloseChange"
              />
            </div>
          </template>
          <template #default="{ row }: TableItem">
            <el-time-picker
              class="!w-full"
              v-model="row.CloseTime"
              format="HH:mm:ss"
              value-format="HH:mm:ss"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="CancelEnable">
          <template #header>
            <div class="flex items-center justify-center">
              <el-tooltip effect="dark" placement="bottom">
                <template #content>
                  <div>
                    取消注单需满足三个条件：<br />
                    ①游戏未封盘<br />
                    ②游戏设置中开启允许取消注单<br />
                    ③打盘报表中设置飞单模式为：距离封盘N秒飞，且游戏倒计时大于N秒
                  </div>
                </template>
                <el-icon class="!text-[18px] mr-[5px]">
                  <Warning />
                </el-icon>
              </el-tooltip>
              <span>是否允许取消注单</span>
            </div>
            <div>
              <el-switch
                size="large"
                inline-prompt
                active-text="是"
                inactive-text="否"
                v-model="state.cancelEnable"
              />
            </div>
          </template>
          <template #default="{ row }: TableItem">
            <el-switch
              size="large"
              inline-prompt
              active-text="是"
              inactive-text="否"
              v-model="row.CancelEnable"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pb-[15px] flex justify-between">
      <div>
        <el-alert
          title="注意：提前封盘时间请参考盘内封盘时间设置，最优选择是比盘内提前封盘，否则可能导致飞单失败。"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>
      <el-button
        v-if="premsStore.isEditGameSetting"
        :loading="state.updating"
        :disabled="state.updating"
        type="primary"
        @click="handleSubmit"
        >保存设置</el-button
      >
    </div>
  </div>
</template>
<script setup lang="ts">
import { reqGameSettingSwitch } from "@/api/setting";
import { cloneDeep, debounce } from "lodash-es";
import { message } from "@/utils/message";
import { useGameStore } from "@/store/modules/game";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: GameListMo;
}

const state = reactive({
  loading: false,
  updating: false,
  status: false,
  cancelEnable: false,
  closeCount: <number | null>null,
  openTime: <string | null>null,
  closeTime: <string | null>null,
  defaultTime: null,
  list: <GameListMo[]>[],
  cloneList: <GameListMo[]>[],
  cacheList: <GameListMo[]>[]
});
const gameStore = useGameStore();
const premsStore = usePremsStore();
const getData = async () => {
  try {
    state.loading = true;
    const data = await gameStore.actionGameList();
    state.loading = false;
    state.list = data;
    state.list.sort((a, b) => a.LotterySort - b.LotterySort);
    state.cloneList = cloneDeep(state.list);
    const allStatus = state.list.filter(item => item.Status == 1);
    const allCancelEnable = state.list.filter(item => item.CancelEnable == 1);
    state.status = allStatus.length == state.list.length;
    state.cancelEnable = allCancelEnable.length == state.list.length;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const handleSubmit = debounce(
  async () => {
    try {
      state.updating = true;
      await reqGameSettingSwitch({
        List: state.list.map(item => {
          return {
            LotteryId: item.LotteryId,
            Status: item.Status,
            CancelEnable: item.CancelEnable,
            LotterySort: Number(item.LotterySort),
            CloseCount: Number(item.CloseCount),
            OpenTime: item.OpenTime,
            CloseTime: item.CloseTime
          };
        })
      });
      state.updating = false;
      message.success("保存成功");
      gameStore.actionGameTotal();
      getData();
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

const handleCloseChange = (val: string) => {
  if (val == "" || val == null) {
    state.list = state.list.map(item => {
      const cur = state.cloneList.find(jtem => jtem.LotteryId == item.LotteryId);
      if (cur) {
        item.CloseTime = cur.CloseTime;
      }
      return item;
    });
  } else {
    state.list = state.list.map(item => {
      return {
        ...item,
        CloseTime: val
      };
    });
  }
};

const handleOpenChange = (val: string) => {
  if (val == "" || val == null) {
    state.list = state.list.map(item => {
      const cur = state.cloneList.find(jtem => jtem.LotteryId == item.LotteryId);
      if (cur) {
        item.OpenTime = cur.OpenTime;
      }
      return item;
    });
  } else {
    state.list = state.list.map(item => {
      return {
        ...item,
        OpenTime: val
      };
    });
  }
};

watch(
  () => state.status,
  val => {
    state.list.forEach(item => {
      item.Status = val ? 1 : 0;
    });
  }
);

watch(
  () => state.cancelEnable,
  val => {
    state.list.forEach(item => {
      item.CancelEnable = val ? 1 : 0;
    });
  }
);

watch(
  () => state.closeCount,
  val => {
    if (val && val !== 0) {
      state.list.forEach(item => {
        item.CloseCount = val;
      });
    } else {
      state.list.forEach(item => {
        const cur = state.cloneList.find(jtem => jtem.LotteryId == item.LotteryId);
        if (cur) {
          item.CloseCount = cur.CloseCount;
        }
      });
    }
  }
);

onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
:deep() {
  .el-input,
  .el-textarea {
    --el-input-bg-color: #f9f9f9;
  }
  .el-table td.el-table__cell .el-switch {
    height: auto;
  }
}
</style>
